package com.drinkian.alipay.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.drinkian.alipay.config.ALiPayConfig;
import com.drinkian.alipay.entity.vo.VOrder;
import com.drinkian.alipay.service.IALiPayService;
import com.drinkian.alipay.util.ALiPayClientUtil;
import com.drinkian.business.good.entity.po.Good;
import com.drinkian.business.good.mapper.GoodMapper;
import com.drinkian.business.record.entity.po.Record;
import com.drinkian.business.record.mapper.RecordMapper;
import com.drinkian.business.room.entity.po.Room;
import com.drinkian.business.room.mapper.RoomMapper;
import com.drinkian.entity.RequestResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Service
public class ALiPayServiceImpl implements IALiPayService {

    @Autowired
    private RecordMapper recordMapper;
    @Autowired
    private GoodMapper goodMapper;
    @Autowired
    private RoomMapper roomMapper;

    @Override
    public RequestResult toPay(VOrder vOrder) throws AlipayApiException {
        AlipayClient alipayClient = ALiPayClientUtil.getInstance();
        AlipayTradePagePayRequest payRequest = new AlipayTradePagePayRequest();

        payRequest.setNotifyUrl(ALiPayConfig.notify_url);
        payRequest.setReturnUrl(ALiPayConfig.return_url);

        Record record = new Record();
        BeanUtils.copyProperties(vOrder, record);
        record.setPrice(String.valueOf((int) (Double.valueOf(record.getPrice()) * 100)));
        recordMapper.insert(record);

        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", record.getId());
        bizContent.put("total_amount", vOrder.getPrice());
        bizContent.put("subject", vOrder.getSubject());
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");

        payRequest.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse payResponse = alipayClient.pageExecute(payRequest);

        if (payResponse.isSuccess()) {
            return new RequestResult(HttpStatus.OK.value(), payResponse.getBody());
        } else {
            return new RequestResult(HttpStatus.INTERNAL_SERVER_ERROR.value(), "调用失败！");
        }
    }

    @Override
    public void payCallback(HttpServletRequest request, HttpServletResponse response) throws AlipayApiException {
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        // 切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
        // boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        boolean flag = AlipaySignature.rsaCheckV1(params, ALiPayConfig.alipay_public_key, ALiPayConfig.charset, "RSA2");

        UpdateWrapper<Record> updateWrapper = new UpdateWrapper<>();
        // 根据支付宝订单号找到对应订单记录
        updateWrapper.eq("id", params.get("out_trade_no"));
        // 更新订单状态为买家已支付
        updateWrapper.set("status", 1);
        int updateResult = recordMapper.update(null, updateWrapper);

        // 获取订单对象
        Record record = recordMapper.selectOne(new QueryWrapper<Record>().eq("id", params.get("out_trade_no")));
        // 更改商品、房屋状态为已售出
        if (record.getType() == 1) {
            UpdateWrapper<Good> goodUpdateWrapper = new UpdateWrapper<Good>();
            goodUpdateWrapper.eq("id", record.getItemId());
            goodUpdateWrapper.set("status", 3);
            goodMapper.update(null, goodUpdateWrapper);
        } else if (record.getType() == 2) {
            UpdateWrapper<Room> roomUpdateWrapper = new UpdateWrapper<Room>();
            roomUpdateWrapper.eq("id", record.getItemId());
            roomUpdateWrapper.set("status", 3);
            roomMapper.update(null, roomUpdateWrapper);
        }
    }
}
